package com.hyt.it.ogt.kq.service.gov.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.hyt.it.ogt.kq.common.gov.constant.ResponseCode;
import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.service.gov.mapper.RegisterInfoMapper;
import com.hyt.it.ogt.kq.service.gov.model.dto.RegisterStatisticsDTO;
import com.hyt.it.ogt.kq.service.gov.model.entity.RegisterInfo;
import com.hyt.it.ogt.kq.service.gov.model.entity.Task;
import com.hyt.it.ogt.kq.service.gov.model.entity.TaskArea;
import com.hyt.it.ogt.kq.service.gov.model.entity.TaskRoom;
import com.hyt.it.ogt.kq.service.gov.model.excel.handler.CustomCellWriteHandler;
import com.hyt.it.ogt.kq.service.gov.model.param.RegisterParam;
import com.hyt.it.ogt.kq.service.gov.model.vo.RegisterStatisticsVO;
import com.hyt.it.ogt.kq.service.gov.model.vo.RegisterVO;
import com.hyt.it.ogt.kq.service.gov.service.IRegisterInfoService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskAreaService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskRoomService;
import com.hyt.it.ogt.kq.service.gov.service.ITaskService;
import com.hyt.it.ogt.kq.common.gov.utils.TextUtil;
import com.hyt.model.PageParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * <p>
 * 注册信息表 服务实现类
 * </p>
 *
 * @author liuq
 * @since 2021-05-08
 */
@Service
public class RegisterInfoServiceImpl extends BaseServiceImpl<RegisterInfoMapper, RegisterInfo> implements IRegisterInfoService {

	@Autowired
	RegisterInfoMapper registerInfoMapper;
	
	@Autowired
	private ITaskRoomService iTaskRoomService;

	@Autowired
	private ITaskService iTaskService;

	@Resource
	private ConfigManager configManager;

	@Autowired
	private ITaskAreaService iTaskAreaService;

	@Override
	public Page<RegisterVO> page(PageParam<RegisterVO> pageParam, RegisterParam param) {
		Page<RegisterVO> registerVoPage = registerInfoMapper.selectRegisterPage(pageParam, param);
		Map<String, TaskArea> taskAreaMap = iTaskAreaService.getTaskAreaMap(param.getTaskId());
		if(!taskAreaMap.isEmpty()){
			List<RegisterVO> records = registerVoPage.getRecords();
			records.forEach(item->{
				TaskArea province = taskAreaMap.get(item.getProvince());
				//1.省不为空
				if(TextUtil.isNotNull(province)){
					item.setProvince(province.getName());
				}
				//2.市不为空
				TaskArea city = taskAreaMap.get(item.getCity());
				if(TextUtil.isNotNull(city)){
					item.setCity(city.getName());
				}
				//3.县区不为空
				TaskArea district = taskAreaMap.get(item.getDistrict());
				if(TextUtil.isNotNull(district)){
					item.setDistrict(district.getName());
				}
			});
			registerVoPage.setRecords(records);
		}

		return registerVoPage;
	}

	@Override
	public RegisterStatisticsVO statistics(RegisterParam param) {
		RegisterStatisticsVO statisticsVO = new RegisterStatisticsVO();
		List<RegisterStatisticsDTO> list = registerInfoMapper.statistics(param);
		for (RegisterStatisticsDTO statisticsDTO : list) {
			if (statisticsDTO.getRegistered() != null) {
				if (statisticsDTO.getRegistered()) {
					statisticsVO.setRegistered(statisticsDTO.getCount());
				} else {
					statisticsVO.setUnregistered(statisticsDTO.getCount());
				}
			}
		}

		// 注册地址
		Task task = iTaskService.getTaskById(param.getTaskId());
		if(task != null) {
			statisticsVO.setRegistAddress(configManager.getExaminationUrl() + task.getCode());
		}
		return statisticsVO;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void clean(String roomId) throws Exception {
		//更新考场表是否注册字段
		iTaskRoomService.lambdaUpdate()
			.eq(TaskRoom::getId, roomId)
			.set(TaskRoom::getRegistered, false)
			.update();
		//删除注册信息
		this.lambdaUpdate()
			.eq(RegisterInfo::getRoomId, roomId)
			.set(RegisterInfo::getDelFlag, true)
			.update();
	}

	@Override
	public boolean add(RegisterInfo registerInfo) {
		return save(registerInfo);
	}

	@Override
	public RegisterInfo getByTaskAndRoomCode(String taskCode, String roomCode) {
		return registerInfoMapper.getByTaskAndRoomCode(taskCode, roomCode);
	}

	@Override
	public void export(HttpServletResponse response, RegisterParam param) throws IOException, KqException {
		List<RegisterVO> registerVOList = registerInfoMapper.export(param);
		// 处理地区
		Map<String, TaskArea> taskAreaMap = iTaskAreaService.getTaskAreaMap(param.getTaskId());
		for (RegisterVO registerVO : registerVOList){
			registerVO.setCity(taskAreaMap.get(registerVO.getCity())==null?null:taskAreaMap.get(registerVO.getCity()).getName());
			registerVO.setProvince(taskAreaMap.get(registerVO.getProvince())==null?null:taskAreaMap.get(registerVO.getProvince()).getName());
			registerVO.setDistrict(taskAreaMap.get(registerVO.getDistrict())==null?null:taskAreaMap.get(registerVO.getDistrict()).getName());
		}

		Task task = iTaskService.getTaskById(param.getTaskId());
		if(null == task){
			throw new KqException(ResponseCode.PLACE_ROOM_EXPORT_REGISTER_DATA_EXCEPTION.getCode(),
					ResponseCode.PLACE_ROOM_EXPORT_REGISTER_DATA_EXCEPTION.getMsg());
		}

		// 考场注册地址
		if(!CollectionUtils.isEmpty(registerVOList)){
			registerVOList.get(0).setRegistAdress(configManager.getExaminationUrl() + task.getCode());
		}

		// 导出Excel
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding("utf-8");
		// 防止中文乱码
		String fileName = URLEncoder.encode("考场注册信息表", "UTF-8");
		response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), RegisterVO.class)
				.registerWriteHandler(new CustomCellWriteHandler())
				.sheet("考场注册信息表")
				.doWrite(registerVOList);
	}

	@Override
	public RegisterInfo getByRoomId(String roomId) {
		QueryWrapper<RegisterInfo> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda()
				.eq(RegisterInfo::getRoomId, roomId)
				.eq(RegisterInfo::getDelFlag, false)
				.last("LIMIT 1");
		return getOne(queryWrapper);
	}

	@Override
	public Boolean monitorRegistered(String taskCode, String mac) {
		return baseMapper.monitorRegistered(taskCode, mac);
	}

	@Override
	public boolean roomRegistered(String roomId) {
		Optional<RegisterInfo> optional = this.lambdaQuery()
				.select(RegisterInfo::getId)
				.eq(RegisterInfo::getRoomId, roomId)
				.eq(RegisterInfo::getDelFlag, false)
				.last("LIMIT 1")
				.oneOpt();
		return optional.isPresent();
	}

}
